package com.bytz.modules.cms.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bytz.common.system.query.MPJLambdaWrapperEx;
import com.bytz.common.system.query.MPJQueryGenerator;
import com.bytz.common.util.SecurityUtils;
import com.bytz.modules.cms.common.constants.AdminAuthConstants;
import com.bytz.modules.cms.common.util.ExcelUtil;
import com.bytz.modules.cms.order.constant.OrderConstants;
import com.bytz.modules.cms.order.constant.OrderPayConstants;
import com.bytz.modules.cms.order.entity.Order;
import com.bytz.modules.cms.order.entity.OrderPay;
import com.bytz.modules.cms.order.entity.OrderPickUpDetail;
import com.bytz.modules.cms.order.mapper.OrderPickUpDetailMapper;
import com.bytz.modules.cms.order.model.OrderPickUpDetailExcel;
import com.bytz.modules.cms.order.model.OrderPickUpDetailModel;
import com.bytz.modules.cms.order.service.IAdminOrderPickUpDetailService;
import com.bytz.modules.cms.reseller.entity.Reseller;
import com.bytz.modules.cms.user.constants.CmsSysUserConstants;
import com.bytz.modules.cms.user.service.ICmsSysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class AdminOrderPickUpDetailServiceImpl extends ServiceImpl<OrderPickUpDetailMapper, OrderPickUpDetail> implements IAdminOrderPickUpDetailService {

    @Autowired
    private ICmsSysUserService sysUserService;

    /**
     * 构造wrapper
     * @param initQueryWrapper initQueryWrapper
     */
    private void constructWrapper(MPJLambdaWrapperEx<OrderPickUpDetail> initQueryWrapper){
        // 销售只能看到自己的订单，大区经理只能看到自己区域销售的订单 订单管理员只能看到自己对应销售的订单
        if (!SecurityUtils.hasAuthority(AdminAuthConstants.Order.PICK_UP_VIEW_ALL)) {
            boolean isRegionManager = SecurityUtils.hasRole(CmsSysUserConstants.RoleCode.REGION_SALES_MANAGER);
            boolean isOrderManager = SecurityUtils.hasRole(CmsSysUserConstants.RoleCode.ORDER_MANAGER);
            initQueryWrapper.and(wrapper -> {
                wrapper.eq(Order::getSalesId, SecurityUtils.getLoginUser().getId());
                if (isRegionManager) {
                    List<String> salesIds = sysUserService.getSalesIdsByRegionManager(SecurityUtils.getLoginUser().getId());
                    if (CollectionUtil.isNotEmpty(salesIds)) {
                        wrapper.or().in(Order::getSalesId, salesIds);
                    }
                }
                if (isOrderManager) {
                    Set<String> salesIds = sysUserService.getSalesIdsByOM(SecurityUtils.getLoginUser().getId());
                    if (CollectionUtil.isNotEmpty(salesIds)) {
                        wrapper.or().in(Order::getSalesId, salesIds);
                    }
                }
            });
        }
        initQueryWrapper
                .selectAll(OrderPickUpDetail.class)
                .select(Order::getDemanderName,
                        Order::getDemanderNumber,
                        Order::getShipToAddress,
                        Order::getShipToName,
                        Order::getShipToPhone,
                        Order::getShipToNumber,
                        Order::getEcRequired,
                        Order::getShipToContact,
                        Order::getContractNumber,
                        Order::getSapSalesOrderId)
                .select(Reseller::getResellerName)
                .select(OrderPay::getCompleteDateTime)
                .innerJoin(Order.class, on -> on
                        .eq(Order::getId, OrderPickUpDetail::getOrderId)
                        .ne(Order::getStatus, OrderConstants.OrderStatus.YI_ZHONG_ZHI))
                .innerJoin(Reseller.class, Reseller::getId, Order::getResellerId)
                .innerJoin(OrderPay.class, OrderPay::getId, OrderPickUpDetail::getOrderPayId)
                .eq(OrderPickUpDetail::getStatus, OrderPayConstants.PayStatus.DONE);
    }


    @Override
    public IPage<OrderPickUpDetailModel> queryPage(Page<OrderPickUpDetail> requestPage, OrderPickUpDetailModel orderPickUpDetail, Map<String, String[]> parameterMap) throws Exception {
        MPJLambdaWrapperEx<OrderPickUpDetail> wrapper = MPJQueryGenerator.initQueryWrapper(orderPickUpDetail, parameterMap, OrderPickUpDetail.class);
        constructWrapper(wrapper);
        return baseMapper.selectJoinPage(requestPage, OrderPickUpDetailModel.class, wrapper);
    }

    @Override
    public void export(OrderPickUpDetailModel orderPickUpDetail, Map<String, String[]> parameterMap, HttpServletResponse response) throws Exception {
        MPJLambdaWrapperEx<OrderPickUpDetail> wrapper = MPJQueryGenerator.initQueryWrapper(orderPickUpDetail, parameterMap, OrderPickUpDetail.class);
        constructWrapper(wrapper);
        List<OrderPickUpDetailModel> orderPickUpDetailModels = baseMapper.selectJoinList(OrderPickUpDetailModel.class, wrapper);
        List<OrderPickUpDetailExcel> excelList = BeanUtil.copyToList(orderPickUpDetailModels, OrderPickUpDetailExcel.class);

        ExcelUtil.export("导出提货列表", OrderPickUpDetailExcel.class, response, excelList);

    }
}
